package shaizi

import (
	. "enca/module/db"
	"fmt"
	"html/template"
	"log"
	"net/http"

	"golang.org/x/net/websocket"
)

//房间信息
type Room struct {
	Id         int    `json:"id,omitempty" form:"id" db:"id"`
	CreateTime string `json:"create_time,omitempty" form:"create_time" db:"create_time"`
	WsPath     string `json:"ws_path,omitempty" form:"ws_path" db:"ws_path"`
}

//错误
func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

func Echo(ws *websocket.Conn) {

	var err error

	for {

		var reply string

		//websocket接受信息

		if err = websocket.Message.Receive(ws, &reply); err != nil {

			fmt.Println("接受失败:", err)

			break

		}

		fmt.Println("reveived from client: " + reply)

		msg := "received:" + reply

		fmt.Println("send to client:" + msg)

		//这里是发送消息

		if err = websocket.Message.Send(ws, msg); err != nil {

			fmt.Println("发送失败:", err)

			break

		}

	}

}

func web(w http.ResponseWriter, r *http.Request) {

	//打印请求的方法

	fmt.Println("method", r.Method)

	if r.Method == "GET" { //如果请求方法为get显示login.html,并相应给前端

		t, _ := template.ParseFiles("websocket.html")

		t.Execute(w, nil)

	} else {

		//否则走打印输出post接受的参数username和password

		fmt.Println(r.PostFormValue("username"))

		fmt.Println(r.PostFormValue("password"))

	}

}

func Open() {
	//接受websocket的路由地址

	http.Handle("/websocket", websocket.Handler(Echo))

	//html页面

	http.HandleFunc("/web", web)

	if err := http.ListenAndServe(":9091", nil); err != nil {

		log.Fatal("ListenAndServe:", err)

	}
}

func JoinRoom(id string) (code int, data interface{}) {
	var room []Room

	err := Db.Select(&room, "SELECT * FROM blog_list where id="+id+" order by release_time desc")
	checkErr(err)

	if len(room) > 0 {
		code = 200
		data = room
	} else {
		code = 500
		data = "找不到房间"
	}

	return
}
